import { deptApi } from '@/apis'
import { TableRefHook } from '@/hooks'

import { useDeptForm } from '.'

type Params = {
  tableRefHook: TableRefHook
  getDeptTree: Func
}

export function useToolbar({ tableRefHook, getDeptTree }: Params) {
  const {
    show: showAdd,
    loading: addLoading,
    formModel: addFormModel,
    formRef: addFormRef
  } = useDeptForm()

  function handleShowAdd(parentId?: string) {
    if (parentId) {
      addFormModel.value.parentId = parentId
    }

    showAdd.value = true
    getDeptTree()
  }

  function handleCloseAdd() {
    showAdd.value = false
  }

  function handleAdd() {
    addFormRef.validate().then(async () => {
      try {
        addLoading.value = true

        await deptApi.createDept(addFormModel.value)

        addLoading.value = false
        handleCloseAdd()

        await tableRefHook.refresh()
        tableRefHook.tableRef.value.setAllTreeExpand(true)
      } catch {
        addLoading.value = false
      }
    })
  }

  function handleToggleExpand() {
    const treeExpandRecords = tableRefHook.tableRef.value.getTreeExpandRecords()

    treeExpandRecords.length > 0
      ? tableRefHook.tableRef.value.clearTreeExpand()
      : tableRefHook.tableRef.value.setAllTreeExpand(true)
  }

  return {
    showAdd,
    addLoading,
    addFormModel,
    addFormRef,
    handleShowAdd,
    handleCloseAdd,
    handleAdd,
    handleToggleExpand
  }
}
